﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ManageSystem.Dialog;
using Shared.Model;
using SharedClientDll;
using System.IO;

namespace ManageSystem.Manager
{
    public partial class FormStatisticsOut : UserControl
    {
        public FormStatisticsOut()
        {
            InitializeComponent();
        }

        private void ButtonSearch_Click(object sender, EventArgs e)
        {
            try
            {
                Shared.SoftMethod.SoftShared.SetControl(this, this.richTextBoxMsg, string.Empty);

                int startHour = int.Parse(this.comboBoxStartHour.Text.Trim());
                int countHour = int.Parse(this.comboBoxCount.Text.Trim());
                int cycle = int.Parse(this.textBoxCycle.Text.Trim());
                if (string.IsNullOrEmpty(this.textBoxLineId.Text))
                {
                    MessageBox.Show("请选择产线ID");
                    return;
                }
                long lineId = long.Parse(this.textBoxLineId.Text.Trim());

                //统计周期大于30秒
                if (cycle < 30)
                {
                    MessageBox.Show("统计周期必须大于30秒");
                    Shared.SoftMethod.SoftShared.AppendText(this, this.richTextBoxMsg, "统计周期必须大于30秒");
                    cycle = 30;
                }

                if (countHour > 12)
                {
                    MessageBox.Show("统计时长小于12小时");
                    Shared.SoftMethod.SoftShared.AppendText(this, this.richTextBoxMsg, "统计时长小于12小时");
                    countHour = 12;
                }

                DateTime startTime = this.dateTimePickerStartDate.Value.Date.AddHours(startHour);

                //判断数据是否正确
                if (startTime >= DateTime.Now.AddMinutes(-3))
                {
                    MessageBox.Show("开始时间必须小于当前时间");
                    Shared.SoftMethod.SoftShared.AppendText(this, this.richTextBoxMsg, "开始时间必须小于当前时间");
                    return;
                }

                //得到统计结束时间
                DateTime endTime = startTime.AddHours(countHour);
                if (endTime >= DateTime.Now.AddMinutes(-1))
                {
                    endTime = DateTime.Now.AddMinutes(-1);
                }

                List<NODE> listNode = null;

                //获取line 对应的所有工序ID，有顺序的那种
                NODE nodeW = new NODE();
                nodeW.SetWhere(
                    string.Format("FLAG=1 AND FLOW_ID=(SELECT FLOW_ID FROM LINE WHERE ID={0}) ORDER BY SORT",lineId));
                var selectNode = Client.MethodWcf.SelectNodeClient(nodeW);

                if (selectNode.result == false)
                {
                    MessageBox.Show("未能获得产线对应的工序信息");
                    Shared.SoftMethod.SoftShared.AppendText(this, this.richTextBoxMsg, "未能获得产线对应的工序信息");
                    return;
                }
                else
                {
                    listNode = selectNode.value;
                }

                //获取LINE对应的PROCESS数据
                PROCESS processW = new PROCESS();
                processW.SetWhere(
                    string.Format("LINE_ID={0} AND END_TIME>'{1}' AND END_TIME<='{2}'"
                    , lineId, startTime.ToString("yyyy-MM-dd HH:mm:ss"), endTime.ToString("yyyy-MM-dd HH:mm:ss")));

                var selectProcess = Client.MethodWcf.SelectProcessClient(processW);
                //判断process数量，需要大于100条
                if (selectProcess.result == false || selectProcess.value.Count < 100)
                {
                    Shared.SoftMethod.SoftShared.AppendText(this, this.richTextBoxMsg, "未能获得生产数据/生产数据数量小于100条");
                    return;
                }

                //根据process得到统计的内容
                DataTable dataTable = new DataTable();

                dataTable.Columns.Add(new DataColumn("StartTime"));
                dataTable.Columns.Add(new DataColumn("EndTime"));
                //添加列
                foreach (NODE n in listNode)
                {
                    dataTable.Columns.Add(new DataColumn(n.NAME));
                }

                //添加行数据
                DateTime startTemp = startTime;
                DateTime endTemp = startTime;
                while ((endTemp = endTemp.AddSeconds(cycle)) < endTime)
                {
                    DataRow row = dataTable.NewRow();
                    row["StartTime"] = startTemp.ToString();
                    row["EndTime"] = endTemp.ToString();

                    foreach(NODE n in listNode)
                    {
                        row[n.NAME] = (from p in selectProcess.value
                                       where p.NODE_ID == n.ID && p.END_TIME >= startTemp && p.END_TIME < endTemp
                                       select p.MAC).Distinct().Count();

                        Shared.SoftMethod.SoftShared.AppendText(this, this.richTextBoxMsg, string.Format("添加{0}数据,{1}", n.NAME, row[n.NAME]));
                    }

                    dataTable.Rows.Add(row);

                    startTemp = endTemp;
                }

                //写入数据到EXCEL，当前文件夹下的OUTPUT目录，命令方式为年月日/开始/结束/统计周期/时分.xlsx

                string filePath = string.Format("{0}\\{1}\\{2}", Application.StartupPath, "EXCEL", startTime.ToString("yyyyMM"));

                string outputFile = string.Format("{0}\\{1}_{2}_{3}_{4}.xlsx"
                    , filePath
                    , lineId
                    , startTime.ToString("yyyyMMddHHmmss")
                    , countHour
                    , cycle);

                if (Directory.Exists(filePath) == false)
                {
                    Directory.CreateDirectory(filePath);
                }

                YcdExcelStatic.TableToExcel(dataTable, outputFile);

                MessageBox.Show("统计完成，输出EXCEL位置：" + outputFile);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void textBoxLineId_MouseClick(object sender, MouseEventArgs e)
        {
            DialogLine line = new DialogLine(this.textBoxLineId);
            line.ShowDialog();
        }

        private void richTextBoxMsg_TextChanged(object sender, EventArgs e)
        {
            richTextBoxMsg.SelectionStart = richTextBoxMsg.Text.Length;
            richTextBoxMsg.ScrollToCaret();
        }
    }
}
